package com.example.messagemodule.ui.fragment;

import android.media.MediaPlayer;

import androidx.annotation.NonNull;

import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.constants.ARouterConstants;
import com.example.messagemodule.R;
import com.examination.mlib.customview.surface.OnDoubleClickListener;
import com.examination.mlib.baseold.ModuleBaseFragment;
import com.zzhoujay.richtext.RichText;



import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


public class HealthConsultVideoFragment extends ModuleBaseFragment
        implements View.OnClickListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnErrorListener {

    private String content;
    private String url;
//    private WebView healthConsultArticleWebView;
    private TextView healthconsultVideoContent;

    private RelativeLayout rlayoutVideo;
    private SurfaceView sv;
    private ImageView imageClickplayMoren;
    private ImageView imageClickplay;
    private Button btPause;
    private TextView tvCurrentProgress;
    private SeekBar seekBar;
    private TextView tvTotalProgress;
    private Button btMaxsize;
    private Button btMinisize;





    private Timer timer;
    private TimerTask task;
    private MediaPlayer mediaPlayer;
    private static int savedPosition;
    private SurfaceHolder holder;
    private int screenWidth;
    private int screenHeight;

    @Autowired
    protected int LastCurrentPosition;

    @Override
    public int bondLayout() {
        return R.layout.fragment_health_consult_video;
    }

    @Override
    public void initView() {
        healthconsultVideoContent = (TextView) findViewById(R.id.healthconsult_video_content);
        rlayoutVideo = (RelativeLayout) findViewById(R.id.rlayout_video);
        sv = (SurfaceView) findViewById(R.id.sv);
        imageClickplayMoren = (ImageView) findViewById(R.id.image_clickplay_moren);
        imageClickplay = (ImageView) findViewById(R.id.image_clickplay);
        btPause = (Button) findViewById(R.id.bt_pause);
        tvCurrentProgress = (TextView) findViewById(R.id.tv_currentProgress);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        tvTotalProgress = (TextView) findViewById(R.id.tv_totalProgress);
        btMaxsize = (Button) findViewById(R.id.bt_maxsize);
        btMinisize = (Button) findViewById(R.id.bt_minisize);

        btPause.setOnClickListener(this);
        btMaxsize.setOnClickListener(this);
        btMinisize.setOnClickListener(this);
        imageClickplay.setOnClickListener(this);
        imageClickplayMoren.setOnClickListener(this);



    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    public void setUrl(String url,String content) {
//        this.url = "<video src=\"" + url + "\" controlslist=\"nodownload\" controls=\"controls\" style=\"width: 100%\" >\n" +
//                "your browser does not support the video tag\n" +
//                "</video>";
        this.url = url;
        this.content = content;
    }

    public void refreshFragment(){
//        healthConsultArticleWebView.loadDataWithBaseURL(null,url,"text/html","UTF-8",null);
        if (!TextUtils.isEmpty(content)) {
            RichText.from(content).bind(this)
                    .showBorder(false)
                    .into(healthconsultVideoContent);
        }
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        sv.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
            @Override
            public void onDoubleClick() {
                // TODO Auto-generated method stub
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    //bt_pause.setText(STATE_CONTINUE);
                    videoPlayStateImageRefresh(true);
                    btPause.setBackgroundResource(R.mipmap.videoplayer_pause);
                } else {
                    mediaPlayer.start();
                    //bt_pause.setText(STATE_PAUSE);
                    videoPlayStateImageRefresh(false);
                    btPause.setBackgroundResource(R.mipmap.videoplayer_play);
                    return;
                }
            }
        }));

        holder = sv.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        seekBar.setOnSeekBarChangeListener(this);
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (savedPosition > 0) {//�����¼�������в��Ž��ȡ�
                    try {
                        imageClickplayMoren.setVisibility(View.GONE);
                        btPause.setBackgroundResource(R.mipmap.videoplayer_play);
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(url);
                        mediaPlayer.setDisplay(holder);
                        mediaPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    savedPosition = mediaPlayer.getCurrentPosition();//��ǰ����λ��
                    mediaPlayer.stop();
                    timer.cancel();
                    task.cancel();
                    timer = null;
                    task = null;
                }
            }
        });
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        videoPlayStateImageRefresh(true);
        btPause.setBackgroundResource(R.mipmap.videoplayer_pause);
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
        //=============
        mediaPlayer.seekTo(savedPosition);//开始时是从0开始播放，恢复时是从指定位置开始播放
        seekBar.setMax(mediaPlayer.getDuration());//将进度条的最大值设为文件的总时长
        tvCurrentProgress.setText("00:00");
        tvTotalProgress.setText(String.valueOf(msConvertToMinute(mediaPlayer.getDuration())));
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                seekBar.setProgress(mediaPlayer.getCurrentPosition());//将媒体播放器当前播放的位置赋值给进度条的进度
                //tv_currentprogress.setText("00:05");
            }
        };
        timer.schedule(task, 0, 100);//0秒后执行，每隔100ms执行一次
        //Toast.makeText(MainVideoActivity.this, "开始播放！", 0).show();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.image_clickplay_moren) {
            playUrl();
            imageClickplayMoren.setVisibility(View.GONE);
            btPause.setBackgroundResource(R.mipmap.videoplayer_play);
        } else if (id == R.id.image_clickplay) {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    //bt_pause.setText(STATE_CONTINUE);
                    videoPlayStateImageRefresh(true);
                    btPause.setBackgroundResource(R.mipmap.videoplayer_pause);
                } else {
                    mediaPlayer.start();
                    //bt_pause.setText(STATE_PAUSE);
                    videoPlayStateImageRefresh(false);
                    btPause.setBackgroundResource(R.mipmap.videoplayer_play);
                    return;
                }
            }
        } else if (id == R.id.bt_maxsize){
            int currentPosition = mediaPlayer.getCurrentPosition();
            ARouter.getInstance().build(ARouterConstants.VideoPlayerFullActivity)
                    .withInt("currentPosition",currentPosition)
                    .withString("url",url)
                    .navigation(getActivity(),2001);
            mediaPlayer.pause();
        }else if (id == R.id.bt_minisize){

        }else if (id == R.id.bt_pause) {
            pause();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        tvCurrentProgress.setText(String.valueOf(msConvertToMinute(progress)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(seekBar.getProgress());//停止拖拽时进度条的进度
        tvCurrentProgress.setText(String.valueOf(msConvertToMinute(seekBar.getProgress())));
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }

    public void videoPlayStateImageRefresh(boolean b) {
        if (b) {
            imageClickplay.setVisibility(View.VISIBLE);
        }
        else {
            imageClickplay.setVisibility(View.GONE);
        }
    }

    public String msConvertToMinute(int ms) {
        String partA="00";
        String partB="00";
        int totalsecond=ms/1000;
        int minute=totalsecond/60;
        int second=totalsecond-minute*60;
        if (minute<10) {
            partA="0"+minute;
        }
        else {
            partA=String.valueOf(minute);
        }
        if (second<10) {
            partB="0"+second;
        }
        else {
            partB=String.valueOf(second);
        }
        return (partA+":"+partB);
    }

    public void pause() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                //bt_pause.setText(STATE_CONTINUE);
                videoPlayStateImageRefresh(true);
                btPause.setBackgroundResource(R.mipmap.videoplayer_pause);
            } else {
                mediaPlayer.start();
                //bt_pause.setText(STATE_PAUSE);
                videoPlayStateImageRefresh(false);
                btPause.setBackgroundResource(R.mipmap.videoplayer_play);
                return;
            }
        }
    }

    public void stop() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        btPause.setText("��ͣ");
    }
    public void replay() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            mediaPlayer.seekTo(0);
        }
        btPause.setText("��ͣ");
    }

    public void playUrl() {
        if (!TextUtils.isEmpty(url)) {
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.setDisplay(holder);//****************
                mediaPlayer.prepareAsync();//�첽׼��
//                Toast.makeText(, "׼���У�������Ҫ��ʱ�䡭��", 1).show();
            } catch (Exception e) {
                e.printStackTrace();
//                Toast.makeText(this, "����ʧ�ܣ������Ƿ�������Ȩ��", 0).show();
            }
        } else {
//            Toast.makeText(this, "·������Ϊ��", 0).show();
        }
    }

    public void setSavedPosition(int savedPosition) {
        HealthConsultVideoFragment.savedPosition = savedPosition;

    }



}